package com.noahsloan.nutils.collections;

import java.util.AbstractSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import com.noahsloan.nutils.Equals;
import com.noahsloan.nutils.Hasher;

/**
 * Wrapper around a {@link HashSet} that uses an external hashCode.
 * 
 * @author noah
 * 
 * @param <E>
 */
public class ExternalHashSet<E> extends AbstractSet<E> implements Set<E> {

	protected final Set<ExternalHashBase<E>.HashWrapper> set;

	protected final ExternalHashBase<E> extHash;

	public ExternalHashSet(Hasher<? super E> hash,
			Equals<? super E, ? super E> equals,
			Set<ExternalHashBase<E>.HashWrapper> set) {
		extHash = new ExternalHashBase<E>(hash, equals);
		this.set = set;
	}

	public ExternalHashSet(Hasher<? super E> hash,
			Equals<? super E, ? super E> equals) {
		this(hash, equals, new HashSet<ExternalHashBase<E>.HashWrapper>());
	}

	public boolean add(E o) {
		return set.add(wrap(o));
	}

	public void clear() {
		set.clear();
	}

	@SuppressWarnings("unchecked")
	public boolean contains(Object o) {
		return set.contains(wrap((E) o));
	}

	public boolean containsAll(Collection<?> c) {
		for (Object o : c) {
			if (!contains(o)) {
				return false;
			}
		}
		return true;
	}

	public boolean isEmpty() {
		return set.isEmpty();
	}

	public Iterator<E> iterator() {
		final Iterator<ExternalHashBase<E>.HashWrapper> it = set.iterator();
		return new Iterator<E>() {
			public boolean hasNext() {
				return it.hasNext();
			}

			public E next() {
				return it.next().value;
			}

			public void remove() {
				it.remove();
			}
		};
	}

	/**
	 * 
	 */
	@SuppressWarnings("unchecked")
	public boolean retainAll(Collection<?> c) {
		// create a wrapped version of c
		Set<ExternalHashBase<E>.HashWrapper> cWrapped = new HashSet<ExternalHashBase<E>.HashWrapper>(
				c.size());
		for (Object o : c) {
			cWrapped.add(wrap((E) o));
		}
		return set.retainAll(cWrapped);
	}

	@SuppressWarnings("unchecked")
	public boolean remove(Object o) {
		return set.remove(wrap((E) o));
	}

	public int size() {
		return set.size();
	}

	protected ExternalHashBase<E>.HashWrapper wrap(E value) {
		return extHash.wrap(value);
	}
}
